﻿/*
 * website:http://www.56lea.com  
 * 【博饼】
 * Copyright 2015, 56lea.com
 *
 * Date: 2015-8-5
 * 转载请保留此描述，谢谢，您的支持是我分享成果最大的动力
 */
(function($) {
	jQuery.dice = function() {
		var imgList = [];
		var index = 0;
		var panel;
		var toPos = [300, 500];
		var speed = 5;
		var result = 0;
		var defPos = [];
		var showResult = false;
		var frameNum=0;
		var isStart=false;
		var name = "szPanel" + Math.round(Math.random() * 100000);
		panel = $("<div id='" + name + "' class='" + name + "' style='position:absolute'></div>");
		$(".game").append(panel);
		for (var i = 1; i < 16; i++) {
			var img = $.pq_createImg("img/s" + i + ".png", "." + name, "absolute", "hidden");
			imgList.push(img);
		}
		$(imgList[0]).css("visibility", "initial");
		this.play = function(x, y) {
			defPos = [x, y];
			$(panel).frameAnimate({speed:30}, function() {
				var l = parseInt($(panel).css("left"));
				var t = parseInt($(panel).css("top"));
				var dx = parseInt(defPos[0]);
				var dy = parseInt(defPos[1]);
				$(imgList[index]).css("visibility","hidden");
				index = parseInt(Math.random() * 8) + 7;
				$(imgList[index]).css("visibility","initial");
				if (!showResult&&isStart&&defPos[0] && Math.abs(l - dx) > (5+speed*3) && Math.abs(t - dy) > (5+3*speed)) {
					$(panel).css("left", l + (dx > l ? speed*10 : 0 - speed*10));
					$(panel).css("top", t + (dy > t ? speed*10 : 0 - speed*10));
					return;
				}
				isStart=false;
				defPos=[];
				if (l < toPos[0] - speed * 2) {
					$(panel).css("left", l + speed);
				} else if (l > toPos[0] + speed * 2) {
					$(panel).css("left", l - speed);
				} else if (!showResult) {
					toPos[0] = Math.random() * 200 + 150;
				} else $(panel).css("left", toPos[0]);

				if (t < toPos[1] - speed * 2) {
					$(panel).css("top", t + speed);
				} else if (t > toPos[1] + speed * 2) {
					$(panel).css("top", t - speed);
				} else if (!showResult) {
					toPos[1] = Math.random() * 200 + 200;
				} else $(panel).css("top", toPos[1]);
				if (l == toPos[0] && t == toPos[1]) {
					$(panel).stopFrameAnimate();
					$(imgList[index]).css("visibility", "hidden");
					$(imgList[result]).css("visibility", "initial");
					index = result;
					isStart=true;
					result=0;
					showResult=false;
				}
			});
		}
		this.stop = function(i, x, y) {
			result = i;
			toPos = [x, y];
			showResult = true;
		}
		this.move = function(x, y) {
			$(panel).css("left", x);
			$(panel).css("top", y);
		}
		return {
			imgList: imgList,
			index: index,
			panel: panel,
			toPos: toPos,
			speed: speed,
			result: result,
			defPos: defPos,
			isStart:isStart,
			frameNum:frameNum,
			name:name,
			showResult: showResult,
			play:this.play,
			stop:this.stop,
			move:this.move
		};
	}
})($);